package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.common.wemedia.WemediaContans;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dto.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
@Log4j2
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    WmNewsMaterialService newsMaterialService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //检查数据
        if (multipartFile==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //上传图片
        String fileId=null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //保存素材到数据库
        WmUser user = WmThreadLocalUtils.getUser();
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(user.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断id是否有对应的图片
        WmMaterial material = getById(id);
        if (material==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断该图片是否被引用，如果被引用则不能删
        LambdaQueryWrapper<WmNewsMaterial> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        int count = newsMaterialService.count(wrapper);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前图片被引用");
        }
        //删除fastdfs中的图片
        fastDFSClient.delFile(material.getUrl().replace(fileServerUrl,""));

        //删除数据库的图片
        removeById(id);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 分页条件查询所有,
     * 注意查询的是当前的用户素材，需要加上用户id
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        System.out.println(dto.toString());
        //检查参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
      dto.checkParam();
        //分页查询
        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<>();

        wrapper.eq(dto.getIsCollected()==1,WmMaterial::getIsCollection,dto.getIsCollected());

        //添加用户id查询
        Integer id = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId,id);
        Page<WmMaterial> page=new Page<>(dto.getPage(),dto.getSize());

        IPage<WmMaterial> page1 = page(page, wrapper);

        //返回结果
        PageResponseResult result=new PageResponseResult((int)page1.getCurrent(),(int)page1.getSize(),(int)page1.getTotal());
       result.setData(page1.getRecords());
        return result;
    }

    /**
     * 收藏图片与取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectionMaterial(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial material = getById(id);
        if ( material.getIsCollection()== WemediaContans.COLLECT_MATERIAL){
            material.setIsCollection(WemediaContans.CANCEL_COLLECT_MATERIAL);
        }else {
            material.setIsCollection(WemediaContans.COLLECT_MATERIAL);
        }
       updateById(material);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
